<template>
  <page-header-wrapper :title="false">
    <div class="Role">
      <a-spin tip="加载中..." class="position" v-if="roleLoading"> </a-spin>

      <a-modal
        style="margin-top: 30%"
        width="300px"
        v-model="deleteVisible"
        title="确认信息"
        @cancel="() => (this.deleteVisible = false)"
        @ok="deleteDomain"
        destroyOnClose
      >
        <div>已有记录确定是否删除？</div>
      </a-modal>

      <a-modal
        width="900px"
        v-model="modleVisible"
        :title="form.id ? '编辑资费' : '新增资费'"
        @cancel="() => (this.modleVisible = false)"
        :confirm-loading="formButtonDisableFlag"
        @ok="onSubmit"
        destroyOnClose
      >
        <div id="modalContent">
          <div class="formAspin" v-if="editWaitForLoading">
            <a-spin />
          </div>
          <div class="modalContentForm">
            <a-form-model
              ref="formRef"
              :model="form"
              :rules="rules"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 18 }"
            >
              <a-row type="flex" justify="space-between">
                <a-col :span="12">
                  <Input :form="form" label="模版名称" prop="name" placeholder="请输入模版名称"></Input>
                </a-col>
                <a-col :span="12">
                  <treeSelect
                    :form="form"
                    label="所属组织机构"
                    prop="organizationId"
                    placeholder="请选择所属组织机构"
                    :treeData="oDictionary.organizationsTree"
                  ></treeSelect>
                </a-col>
                <!-- <a-col :span="12">
                  <Select
                    :form="form"
                    label="状态"
                    prop="isEnable"
                    placeholder="请选择状态"
                    :optList="getIsEnableOption()"
                  ></Select>
                </a-col> -->

                <div class="formTitle">
                  <div class="feetitle">
                    收费方式：按时
                    <a-switch class="feeChecked" v-model:checked="feeChecked" @change="feeCheckedChange" />
                  </div>
                  <!-- 收费方式：{{
                    enumsTypeJson[enumsType[0]] && enumsTypeJson[enumsType[0]][0]
                      ? enumsTypeJson[enumsType[0]][0].name
                      : ''
                  }} -->
                  <!-- <a-col :span="12">
                    <Select
                      :form="form"
                      label="收费方式："
                      prop="type"
                      :optList="getFeeType()"
                      placeholder="请选择收费类型"
                      @change="chargeChange"
                    ></Select>
                  </a-col> -->

                  <!-- 动态字段 -->
                  <!-- <template v-for="(domain, index) in form.chargeIntervalsByTime">-->
                  <div v-if="feeChecked">
                    <a-col :span="24" v-for="(item, index) in form.chargeTmplPriceList" :key="index">
                      <a-col :span="10">
                        <!-- :rules="{
                            required: true,
                            message: '请输入收费金额',
                            trigger: 'change',
                          }" -->
                        <InputNumber
                          :labelCol="{ span: 12 }"
                          :wrapperCol="{ span: 12 }"
                          label="收费金额"
                          :form="item"
                          prop="price" :min="0" :max="100"
                          :name="'chargeTmplPriceList.' + index + '.price'"
                          placeholder="请输入收费金额"
                          suffix="元"
                          :precision="2"
                        ></InputNumber>
                      </a-col>
                      <a-col :span="10">
                        <!-- :rules="{
                            required: true,
                            message: '请输入充电时间',
                            trigger: 'change',
                          }" -->
                        <InputNumber
                          :labelCol="{ span: 12 }"
                          :wrapperCol="{ span: 12 }"
                          :form="item"
                          label="充电时间"
                          prop="unit" :min="1"
                          :name="'chargeTmplPriceList.' + index + '.unit'"
                          placeholder="请输入充电时间"
                          suffix="小时"
                          :max="24"
                        ></InputNumber>
                      </a-col>
                      <a-col :span="10">
                        <!-- :rules="{
                            required: true,
                            message: '请输入服务费',
                            trigger: 'change',
                          }" -->
                        <InputNumber
                          :labelCol="{ span: 12 }"
                          :wrapperCol="{ span: 12 }"
                          :form="item"
                          label="服务费" :min="0" :max="100"
                          prop="serviceFee"
                          :name="'chargeTmplPriceList.' + index + '.serviceFee'"
                          placeholder="请输入服务费金额"
                          suffix="元"
                          :precision="2"
                          readonly
                        ></InputNumber>
                      </a-col>
                      <a-col :span="12" style="line-height: 40px; padding-left: 10px">
                        <Button
                          type="stop"
                          v-if="index > 0"
                          :disabled="index === 0"
                          label="删除收费金额"
                          @click="removeDomain(index, item)"
                        />
                      </a-col>
                      <!-- </a-col> -->
                    </a-col>
                    <a-col :span="24" style="padding-bottom: 10px">
                      <a-col :span="3"></a-col>
                      <a-col :span="21">
                        <Button type="reset" label="增加收费金额" @click="addDomainChildren()"></Button>
                      </a-col>
                    </a-col>
                  </div>
                  <!-- </template> -->
                </div>

                <div class="formTitle">
                  <div class="feetitle">
                    收费方式：按量
                    <a-switch class="feeChecked" v-model:checked="rateChecked" @change="rateCheckedChange" />
                  </div>

                  <div v-if="rateChecked">
                    <!-- :rules="{
                          required: true,
                          message: '请输入电费',
                          trigger: 'change',
                        }" -->
                    <a-col :span="10">
                      <InputNumber
                        :labelCol="{ span: 12 }"
                        :wrapperCol="{ span: 12 }"
                        label="电费"
                        :form="form.rateList"
                        prop="price" :min="0" :max="100"
                        :name="'rateList' + '.price'"
                        placeholder="请输入电费"
                        suffix="元/kW·h"
                        :precision="2"
                      ></InputNumber>
                    </a-col>
                    <a-col :span="10">
                      <!-- :rules="{
                          required: true,
                          message: '请输入服务费',
                          trigger: 'change',
                        }" -->
                      <InputNumber
                        :labelCol="{ span: 12 }"
                        :wrapperCol="{ span: 12 }"
                        :form="form.rateList"
                        label="服务费" :min="0" :max="100"
                        prop="serviceFee"
                        :name="'rateList' + '.serviceFee'"
                        placeholder="请输入服务费金额"
                        suffix="元/kW·h"
                        :precision="2"
                      ></InputNumber>
                    </a-col>
                  </div>
                </div>
                <!-- <a-col :span="24">
                  <Button type="search" label="增加时间段" @click="addDomain"></Button>
                  <div style="width: 100%; height: 24px"></div>
                </a-col> -->
                <!-- 动态字段 -->

                <a-col :span="12">
                  <InputNumber
                    :form="form"
                    label="免费占箱时长"
                    prop="occupyFreeDuation"
                    placeholder="请输入免费占箱时长"
                    suffix="小时" :min="0"
                    :max="24"
                  ></InputNumber>
                </a-col>
                <a-col :span="12">
                  <InputNumber
                    :form="form"
                    label="占箱收费上限"
                    prop="occupyChargeUpperLimit"
                    placeholder="请输入最多收费"
                    suffix="元" :min="0" :max="100"
                    :precision="2"
                  ></InputNumber>
                </a-col>
                <a-col :span="12">
                  <InputNumber
                    :form="form"
                    label="每超时间"
                    prop="occupyChargeDuration"
                    placeholder="请输入每超时间"
                    :max="24" :min="0"
                    suffix="小时"
                  ></InputNumber>
                </a-col>
                <a-col :span="12">
                  <InputNumber
                    :form="form"
                    label="每次收费"
                    prop="occupyChargePrice"
                    placeholder="请输入每次收费"
                    suffix="元" :min="0" :max="100"
                    :precision="2"
                  ></InputNumber>
                </a-col>
                <a-col :span="12">
                  <!-- 20220110z 替换控件增加跨天概念 -->
                  <!-- <rangeTimePicker
                    :form="form"
                    label="免费时段"
                    prop="occupyFreeStartTime&occupyFreeEndTime"
                  ></rangeTimePicker> -->
                  <crossTodayTimePicker
                    :form="form"
                    label="免费时段"
                    :isRequired="false"
                    prop="occupyFreeStartTime&occupyFreeEndTime"
                  ></crossTodayTimePicker>
                </a-col>
                <a-col :span="12">
                  <p class="tipstext">若不设置，默认无免费占仓时段</p>
                </a-col>
                <a-col :span="24">
                  <Textarea
                    :labelCol="{ span: 3 }"
                    :wrapperCol="{ span: 21 }"
                    :form="form"
                    label="提示信息"
                    prop="promptDesc"
                    placeholder="请输入提示信息"
                  ></Textarea>
                </a-col>
                <a-col :span="24">
                  <Textarea
                    :labelCol="{ span: 3 }"
                    :wrapperCol="{ span: 21 }"
                    :form="form"
                    label="注意事项"
                    prop="attentionDesc"
                    placeholder="请输入注意事项"
                  ></Textarea>
                </a-col>
              </a-row>
            </a-form-model>
          </div>
        </div>
      </a-modal>
      <typicalSearch ref="insideSearch" :searchConfig="searchConfig" @searchMethod="getTableData"></typicalSearch>
      <div class="table">
        <div class="tableTitle">
          <div class="title">资费设置</div>
          <div class="addButton">
            <a-button type="primary" @click="handleEdit()"> 新增资费 </a-button>
          </div>
        </div>
        <div class="tableList">
          <typicalTable
            ref="insideTable"
            :tableConfig="tableConfig"
            :tableData="tableData"
            @getTableData="getTableData"
          >
            <template v-slot="slotProps">
              <Button label="编辑" @click="handleEdit(slotProps.record)"></Button>
              <a-popconfirm
                slot="action"
                title="此操作将删除该条数据，是否继续?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(slotProps.record)"
              >
                <Button type="stop" label="删除"></Button>
              </a-popconfirm>
              <Button
                :type="slotProps.record.status === 0 ? 'start' : 'stop'"
                @click="fnStartStop(slotProps.record)"
              ></Button>
            </template>
          </typicalTable>
        </div>
      </div>
    </div>
  </page-header-wrapper>
</template>
<script>
import moment from 'moment';
import typicalSearch from '@/components/typicalSearch';
import typicalTable from '@/components/typicalTable';
import Input from '@/components/typicalControl/Input';
import InputNumber from '@/components/typicalControl/InputNumber';
import treeSelect from '@/components/typicalControl/treeSelect';
import Select from '@/components/typicalControl/select';
import rangeDatePicker from '@/components/typicalControl/rangeDatePicker';
import rangeTimePicker from '@/components/typicalControl/rangeTimePicker';
import Textarea from '@/components/typicalControl/textarea';
import Button from '@/components/typicalControl/button';
import crossTodayTimePicker from '@/components/typicalControl/crossTodayTimePicker';
import hourTimePicker from '@/components/typicalControl/hourTimePicker';
import { getListEnumsJson, getIsEnableOption, getFeeType } from '@/utils/frequentInterface';
import { frontToAfterTransformation } from '@/utils/tool';

import { listCharges } from '@/api/cabin';
import { organizationsTree } from '@/api/system';

export default {
  name: 'PostageSettings',
  components: {
    typicalSearch: typicalSearch,
    typicalTable: typicalTable,
    Input: Input,
    treeSelect: treeSelect,
    Select: Select,
    rangeDatePicker: rangeDatePicker,
    InputNumber: InputNumber,
    rangeTimePicker: rangeTimePicker,
    Textarea: Textarea,
    Button: Button,
    crossTodayTimePicker: crossTodayTimePicker,
    hourTimePicker: hourTimePicker,
  },
  data() {
    return {
      deleteVisible: false, //确认删除资费弹框
      domainIndex: null,
      domainDelList: [], //需删除的收费list
      formButtonDisableFlag: false, // 表单确定禁用按钮 防止多次点击多次保存
      editWaitForLoading: false, // 加载编辑回显数据等待Loading
      roleLoading: false, // 加载表格的loading
      modleVisible: false, // 控制弹框
      feeChecked: true, //收费方式 按时
      rateChecked: true, //收费方式 按量
      form: {
        attentionDesc: undefined,
        name: undefined,
        organizationId: undefined,
        occupyChargeDuration: undefined,
        occupyChargeUpperLimit: undefined,
        occupyChargePrice: undefined,
        occupyFreeDuation: undefined,
        'occupyFreeStartTime&occupyFreeEndTime': [],
        promptDesc: undefined,

        status: 1, // 状态
        isSystem: 0,

        chargeTmplPriceList: [
          {
            type: 'DURATION', //收费方式
            price: '', //收费金额
            serviceFee: '0', //服务费
            unit: '', //充电时间 按次/按量传1
          },
        ],
        rateList: {
          type: 'QUANTITY', //收费方式
          price: '', //收费金额
          serviceFee: '', //服务费
          unit: '1', //充电时间 按次/按量传1
        },
      },

      oMapping: {
        isReverse: false,
        occupyFreeStartTime: 'occupyFreeStartTime&occupyFreeEndTime',
        startTime: 'startTime&endTime',
      },
      rules: {
        // 规则验证
        name: [
          { required: true, message: '请输入模板名称', trigger: 'blur' },
          { max: 15, message: '最大长度不能超过15个字符', trigger: 'blur' },
        ],
        organizationId: [{ required: true, message: '请选择所属组织机构', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        occupyChargeDuration: [{ required: true, message: '请输入占箱收费单位时长（小时）', trigger: 'blur' }],
        occupyChargePrice: [{ required: true, message: '请输入占箱收费单价（元）', trigger: 'blur' }],
        occupyChargeUpperLimit: [{ required: true, message: '请输入占箱收费上限', trigger: 'blur' }],
        occupyFreeDuation: [{ required: true, message: '请输入免费占箱时长', trigger: 'blur' }],
        type: [{ required: true, message: '请选择收费方式', trigger: 'blur' }],
        promptDesc: [
          { required: true, message: '请输入提示信息', trigger: 'blur' },
          { max: 255, message: '最大长度不能超过255个字符', trigger: 'blur' },
        ],
        attentionDesc: [
          { required: true, message: '请输入注意事项', trigger: 'blur' },
          { max: 255, message: '最大长度不能超过255个字符', trigger: 'blur' },
        ],
        'occupyFreeStartTime&occupyFreeEndTime': [
          // { type: 'array', required: true, message: '请选择时间区间', trigger: 'change' },
        ],
      },
      // 搜索组件配置
      searchConfig: {
        formItemList: [
          {
            type: 'input',
            prop: 'searchTitle',
            value: '',
            label: '模板名称',
          },
          // ,
          // {
          //   type: 'selectTree',
          //   prop: 'searchCode',
          //   value: '',
          //   label: '组织机构'
          // }
        ],
        parent: this,
      },
      // 列表组件配置
      tableConfig: {
        columns: [
          {
            title: '模板名称',
            dataIndex: 'name',
            ellipsis: true,
          },
          {
            title: '组织机构',
            dataIndex: 'organizationName',
            ellipsis: true,
          },
          {
            title: '免费占箱时长',
            dataIndex: 'occupyFreeDuation',
            customRender: (val) => (val ? val + '小时' : ''),
          },
          {
            title: '免费占箱开始时段',
            dataIndex: 'occupyFreeStartTime',
          },
          {
            title: '免费占箱结束时段',
            dataIndex: 'occupyFreeEndTime',
          },
          {
            title: '状态',
            dataIndex: 'status',
            scopedSlots: { customRender: 'status' },
            width: '80px',
          },
          {
            title: '操作',
            scopedSlots: { customRender: 'action' },
            ellipsis: true,
            width: '160px',
          },
        ],
        pageSize: this.$store.state.user.defaultPaginationPagesize,
        pageSizeOptions: this.$store.state.user.defaultPaginationOptions,
        parent: this,
      },
      // 列表组件数据
      tableData: {
        records: [],
        total: 0,
      },
      enumsType: ['ChargeWay'],
      enumsTypeJson: {},
      checkTimeIntervalRule: [
        {
          parent: 'chargeIntervalsByTime',
          attribute: 'startTime&endTime',
        },
      ],
      oDictionary: {
        organizationsTree: [],
      },
    };
  },
  created() {
    this.getDictionary();
  },
  mounted() {
    this.$refs.insideSearch.searchInfo();
  },
  methods: {
    moment,
    getIsEnableOption,
    getFeeType,
    /**
     * [getDictionary 获取各种字典]
     * @return {[type]} [description]
     */
    getDictionary() {
      this.enumsTypeJson = getListEnumsJson(this.enumsType);
      // 组织列表树形结构数据
      organizationsTree().then((res) => {
        if (res.code == 200) {
          this.oDictionary.organizationsTree = res.data;
        }
      });
    },
    /**
     * [fnStartStop 启用停用方法]
     * @param  {[type]} row [行数据]
     * @return {[type]}     [description]
     */
    fnStartStop(row) {
      this.roleLoading = true;
      listCharges('/updateStatus', 'put', { id: row.id, status: row.status == 1 ? 0 : 1 })
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(row.status == 1 ? '停用成功' : '启用成功');
            this.formSuccessOperation(res);
          } 
        })
        .finally(() => {
          this.roleLoading = false;
        });
    },
    /**
     * [getTableData 获取表格数据]
     * @param  {[type]} searchParam [搜索条件]
     * @return {[type]}             [description]
     */
    getTableData(searchParam) {
      if (!searchParam) throw new Error('getTableData 没有入参搜索条件！');
      this.roleLoading = true;
      searchParam.searchDataRang = 9;
      let name = searchParam.searchTitle ? searchParam.searchTitle : '';
      listCharges(
        `/getTmplPageList?pageNum=${searchParam.pageNumber + 1}&pageSize=${
          searchParam.pageSize
        }&name=${name}&organizationId=`,
        'get'
      )
        .then((res) => {
          if (res.code == 200 && res.data.records) {
            this.tableData = res.data;
          } else {
            this.tableData.records = [];
            this.tableData.total = 0;
          }
        })
        .finally(() => {
          this.roleLoading = false;
        });
    },
    /**
     * [initializationForm 初始化form数据]
     * @return {[type]} [description]
     */
    initializationForm() {
      return {
        attentionDesc: undefined,
        name: undefined,
        organizationId: undefined,
        occupyChargeDuration: undefined,
        occupyChargeUpperLimit: undefined,
        occupyChargePrice: undefined,
        occupyFreeDuation: undefined,
        'occupyFreeStartTime&occupyFreeEndTime': [],
        promptDesc: undefined,

        status: 1, // 状态
        isSystem: 0,
        chargeTmplPriceList: [
          {
            type: 'DURATION', //收费方式
            price: '', //收费金额
            serviceFee: '0', //服务费
            unit: '', //充电时间 按次/按量传1
          },
        ],
        rateList: {
          type: 'QUANTITY', //收费方式
          price: '', //收费金额
          serviceFee: '', //服务费
          unit: '1', //充电时间 按次/按量传1
        },
      };
    },
    // chargeChange(e) {
    //   console.log(e);
    // },

    feeCheckedChange(e) {
      if (!e && !this.rateChecked) {
        this.rateChecked = true;
      }
      if (this.rateChecked && (!this.rateList || this.rateList.length == 0)) {
        this.rateList = {
          type: 'QUANTITY', //收费方式
          price: '', //收费金额
          serviceFee: '', //服务费
          unit: '1', //充电时间 按次/按量传1
        };
      }
    },
    rateCheckedChange(e) {
      if (!e && !this.feeChecked) {
        this.feeChecked = true;
      }
      if (this.rateChecked && (!this.rateList || this.rateList.length == 0)) {
        this.rateList = {
          type: 'QUANTITY', //收费方式
          price: '', //收费金额
          serviceFee: '', //服务费
          unit: '1', //充电时间 按次/按量传1
        };
      }
    },
    /**
     * @description: 新增编辑资费表单提交
     */
    onSubmit() {
      // if (this.isTimeIntervalOverlap(this.form, this.checkTimeIntervalRule)) {
      //   return false;
      // }
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // var prepareJson = {};
          // this.oMapping.isReverse = false;
          // frontToAfterTransformation(prepareJson, this.form, this.oMapping);
          // 按照开始时间从小到大排序
          // this.chargeIntervalsByTimeSort(prepareJson.chargeIntervalsByTime);
          this.formButtonDisableFlag = true;
          if (this.form.id) {
            this.editRole(this.form);
          } else {
            this.roleAdd(this.form);
          }
        } else {
          return false;
        }
      });
    },

    /**
     * [chargeIntervalsByTimeSort 表单chargeIntervalsByTime排序]
     * @param  {[type]} arr [待排序数组]
     * @return {[type]}     [description]
     */
    chargeIntervalsByTimeSort(arr) {
      const self = this;
      arr.sort(function (a, b) {
        return self.timeToSec(a.startTime) - self.timeToSec(b.startTime);
      });
    },

    /**
     * @description: 新增资费
     * @param {object} addRoleParam 表单参数
     */
    roleAdd(addRoleParam) {
      let params= this.detealParam(addRoleParam);
      let chargeList = params.chargeTmplPriceList;
      if (!this.feeChecked) {
          chargeList = chargeList.filter((item) => (item.type == 'QUANTITY' || item.type == '按量'));
      }
       if (!this.rateChecked) {
          chargeList = chargeList.filter((item) => (item.type == 'DURATION' || item.type == '按时'));
      }
      params.chargeTmplPriceList = chargeList;
      listCharges('/insertChargeTmpl', 'post', params)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('新增成功');
            this.formSuccessOperation(res);
          } 
        })
        .finally(() => {
          this.formButtonDisableFlag = false;
        });
    },
    detealParam(param) {
      let {
        attentionDesc,
        name,
        organizationId,
        occupyChargeDuration,
        occupyChargeUpperLimit,
        occupyChargePrice,
        occupyFreeDuation,
        promptDesc,
        chargeTmplPriceList,
      } = { ...param };
      let params = {
        attentionDesc,
        name,
        organizationId,
        occupyChargeDuration,
        occupyChargeUpperLimit,
        occupyChargePrice,
        occupyFreeDuation,
        promptDesc,
        chargeTmplPriceList,
      };

      let rate = params.chargeTmplPriceList.filter((item) => item.type == 'QUANTITY' || item.type == '按量');
      if (this.rateChecked && rate.length == 0) {
        params.chargeTmplPriceList.push(param.rateList);
      }
      params.chargeTmplPriceList.forEach((item) => {
        if (item.type == '按量') {
          item.type = 'QUANTITY';
        }
        if (item.type == '按时') {
          item.type = 'DURATION';
        }
      });
      params.occupyFreeStartTime = param['occupyFreeStartTime&occupyFreeEndTime'][0];
      params.occupyFreeEndTime = param['occupyFreeStartTime&occupyFreeEndTime'][1];
      return params;
    },

    /**
     * @description: 编辑资费
     * @param {object} editRoleParam 表单参数
     */
    editRole(editRoleParam) {
      let params = this.detealParam(editRoleParam);
      params.id = editRoleParam.id;
      this.domainDelList.forEach((item) => {
        item.logicDelete = 1;
      });

      let chargeList = params.chargeTmplPriceList;

      chargeList.forEach((item) => {
        if (item.id) item.logicDelete = 0;
        
        if (!this.feeChecked && (item.type == 'DURATION' || item.type == '按时')) {
          if (item.id) item.logicDelete = 1;
        }
        if (!this.rateChecked && (item.type == 'QUANTITY' || item.type == '按量')) {
          if (item.id) item.logicDelete = 1;
        }
      });
      if (!this.feeChecked) {
          chargeList = chargeList.filter((item) => (item.id && (item.type == 'DURATION' || item.type == '按时')) || (item.type == 'QUANTITY' || item.type == '按量'));
      }
       if (!this.rateChecked) {
          chargeList = chargeList.filter((item) => (item.id && (item.type == 'QUANTITY' || item.type == '按量')) || (item.type == 'DURATION' || item.type == '按时'));
      }
      // feeChecked: true, //收费方式 按时
      // rateChecked: true, //收费方式 按量

      chargeList = chargeList.concat(this.domainDelList);
      this.form.chargeTmplPriceList = params.chargeTmplPriceList.filter(
        (item) => item.type == 'DURATION' || item.type == '按时'
      );
      let rates = params.chargeTmplPriceList.filter((item) => item.type == 'QUANTITY' || item.type == '按量');
      if (rates.length > 0) {
        this.form.rateList = rates[0];
      }
      params.chargeTmplPriceList = chargeList;
      listCharges('/updateChargeTmpl', 'put', params)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('编辑成功');
            this.formSuccessOperation(res);
          } 
        })
        .finally(() => {
          this.formButtonDisableFlag = false;
        });
    },

    /**
     * @description: 表单新增编辑成功后的公共的代码 （消息提示 搜索框重置 请求表格数据）
     * @param {object} successFormData 表单请求成功后返回的对象
     */
    formSuccessOperation(successFormData) {
      this.modleVisible = false;
      this.$refs.insideTable.updateListData();
    },

    /**
     * [handleEdit 新增或编辑]
     * @param  {[type]} row [如果编辑入参行数据]
     * @return {[type]}     [description]
     */
    handleEdit(row) {
      this.modleVisible = true;
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      this.form = this.initializationForm();
      if (row) {
        this.editWaitForLoading = true;
        this.domainDelList = [];
        // 根据ID请求相应资费的权限 进行回显
        listCharges('/getChargeTmplById', 'get', { id: row.id })
          .then((res) => {
            if (res.code == 200) {
              // this.form = this.initializationForm();
              // this.oMapping.isReverse = true;
              // frontToAfterTransformation(this.form, res.data, this.oMapping, this);
              let datas = res.data;
              let {
                id,
                attentionDesc,
                name,
                organizationId,
                occupyChargeDuration,
                occupyChargeUpperLimit,
                occupyChargePrice,
                occupyFreeDuation,
                promptDesc,
              } = { ...datas };
              this.form = {
                id,
                attentionDesc,
                name,
                organizationId,
                occupyChargeDuration,
                occupyChargeUpperLimit,
                occupyChargePrice,
                occupyFreeDuation,
                promptDesc,
              };
              this.form['occupyFreeStartTime&occupyFreeEndTime'] = datas.occupyFreeStartTime?[datas.occupyFreeStartTime, datas.occupyFreeEndTime]:[];
              this.form.chargeTmplPriceList = datas.chargeTmplPriceList.filter(
                (item) => item.type == 'DURATION' || item.type == '按时'
              );
              this.feeChecked = this.form.chargeTmplPriceList.length > 0 ? true : false;
              let rates = datas.chargeTmplPriceList.filter((item) => item.type == 'QUANTITY' || item.type == '按量');
              this.rateChecked = rates.length > 0 ? true : false;
              if (rates.length > 0) {
                this.form.rateList = rates[0];
              } else {
                this.form.rateList = {
                  type: 'QUANTITY', //收费方式
                  price: '', //收费金额
                  serviceFee: '', //服务费
                  unit: '1', //充电时间 按次/按量传1
                };
              }
            }
          })
          .finally(() => {
            this.editWaitForLoading = false;
          });
      }
    },

    /**
     * @description: 点击删除
     * @param {object} roleTableRowData 格某一行的数据对象
     */
    handleDelete(roleTableRowData) {
      listCharges(`/updateById?id=${roleTableRowData.id}`, 'put').then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.$refs.insideTable.updateListData();
        } 
      });
    },
    // 动态表单方法
    /**
     * [removeDomain 公共删除]
     * @param  {[type]} parent [所在数组]
     * @param  {[type]} item   [当前数据]
     * @return {[type]}        [description]
     */
    removeDomain(index, item) {
      if (item.id) {
        this.deleteVisible = true;
        this.domainIndex = index;
      } else {
        this.form.chargeTmplPriceList.splice(this.domainIndex, 1);
        this.$forceUpdate();
      }
    },
    deleteDomain() {
      this.deleteVisible = false;
      this.domainDelList.push(this.form.chargeTmplPriceList[this.domainIndex]);
      this.form.chargeTmplPriceList.splice(this.domainIndex, 1);
      this.$forceUpdate();
    },
    /**
     * [addDomain 增加时间区间]
     */
    addDomain() {
      this.form.chargeIntervalsByTime.push({
        'startTime&endTime': [],
        // 按钮设置添加资费方式，1:按时[DURATION]，2:按量[POWER]，3:按次[PACKAGE]
        chargeWay: '1',
        chargeIntervalPrices: [
          {
            cost: '',
            unitVolume: '',
          },
        ],
        key: Date.now(),
      });
    },
    /**
     * [addDomainChildren 增加时间收费]
     * @param {[type]} parent [所在数组]
     */
    addDomainChildren() {
      let param = {
        type: 'DURATION',
        price: '',
        serviceFee: '0',
        unit: '',
      };
      if (this.form.id) {
        param.logicDelete = 0;
      }
      this.form.chargeTmplPriceList.push(param);
      this.$forceUpdate();
    },
    /**
     * [formatterTime 年月日显示]
     * @param  {[type]} val [description]
     * @return {[type]}     [description]
     */
    formatterTime(val) {
      return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : '';
    },
    /**
     * [isTimeIntervalOverlap 是否时间区间重叠（arr格式时间）]
     * @param  {[type]}  obj   [校验对象]
     * @param  {[type]}  aRule [校验规则]
     * @return {Boolean}       [是否]
     */
    isTimeIntervalOverlap(obj, aRule) {
      var aParent, i, j, aFlatten, temporaryObj, k, time1, time2, time3, time4;
      aFlatten = [];
      for (i = 0; i < aRule.length; i++) {
        aParent = obj[aRule[i].parent];
        for (j = 0; j < aParent.length; j++) {
          if (aParent[j][aRule[i].attribute].length < 2) {
            console.log('isTimeIntervalOverlap 时间区间位数不足！');
            // 有必填去校验时间为空
            return false;
          }
          temporaryObj = {};
          temporaryObj.a = aParent[j][aRule[i].attribute][0];
          temporaryObj.b = aParent[j][aRule[i].attribute][1];
          aFlatten.push(temporaryObj);
        }
        aFlatten = this.crossTodayFlat(aFlatten);
        for (j = 0; j < aFlatten.length; j++) {
          for (k = 0; k < aFlatten.length; k++) {
            // 跳过自身比较
            if (k === j) {
              continue;
            }
            // https://ask.csdn.net/questions/1092563
            // 不重叠的规则是：区间A的最大值小于区间B的最小值，或区间A的最小值大于区间B的最大值
            time1 = this.timeToSec(aFlatten[j].a);
            time2 = this.timeToSec(aFlatten[j].b);
            time3 = this.timeToSec(aFlatten[k].a);
            time4 = this.timeToSec(aFlatten[k].b);
            if (!(time2 < time3 || time1 > time4)) {
              this.$message.error('时间段' + aFlatten[j].index + ' 与 时间段' + aFlatten[k].index + ' 重叠!');
              return true;
            }
          }
        }
        // 扩展校验，接入平整后的数据
        if (!this.mergeCheckSatisfy24(aFlatten)) {
          return true;
        }
      }
      return false;
    },
    /**
     * [crossTodayFlat 跨天时间分解（24小时制）]
     * @param  {[type]} arr [description]
     * @return {[type]}     [description]
     */
    crossTodayFlat(arr) {
      var aFlat = [];
      for (var i = 0; i < arr.length; i++) {
        if (this.timeToSec(arr[i].a) > this.timeToSec(arr[i].b)) {
          aFlat.push({
            a: arr[i].a,
            b: '23:59:59',
            index: i + 1,
          });
          aFlat.push({
            a: '00:00:00',
            b: arr[i].b,
            index: i + 1,
          });
        } else {
          arr[i].index = i + 1;
          aFlat.push(arr[i]);
        }
      }
      return aFlat;
    },
    /**
     * [timeToSec 小时分秒转换成秒]
     * @param  {[type]} time [小时分秒]
     * @return {[type]}      [秒]
     */
    timeToSec(time) {
      var result = 0;
      if (time && time !== 0) {
        var arr = time.split(':');
        var hour = Number(arr[0]) * 60 * 60;
        var min = Number(arr[1]) * 60;
        var sec = Number(arr[2]);
        result = hour + min + sec;
      }
      return result;
    },
    /**
     * [mergeCheckSatisfy24 合并时间段是否满足24小时]
     * @param  {[type]} aFlatten [isTimeIntervalOverlap里平整后的数据]
     * @return {[type]}          [description]
     */
    mergeCheckSatisfy24(aFlatten) {
      var aHasHour = [];
      var aHackHour = [];
      var startHour, endHour, i;
      for (i = 0; i < aFlatten.length; i++) {
        startHour = aFlatten[i].a ? Number(aFlatten[i].a.split(':')[0]) : 0;
        endHour = aFlatten[i].b ? Number(aFlatten[i].b.split(':')[0]) : 0;
        for (var j = startHour; j < endHour + 1; j++) {
          if (!aHasHour.includes(j)) {
            aHasHour.push(j);
          }
        }
      }
      for (i = 0; i < 24; i++) {
        if (!aHasHour.includes(i)) {
          aHackHour.push(i);
        }
      }
      if (aHackHour.length === 0) {
        return true;
      } else {
        // this.$message.error('时间段缺少 ' + aHackHour.join(',') + ' 小时的设定!');
        this.$message.error('时间段不满足24个小时的设定!');
        return false;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.Role {
  width: 100%;
  height: calc(100vh - 150px);
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  position: relative;
  .position {
    width: 100%;
    height: 100%;
    background: white;
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }
  .table {
    flex: 1;
    background: white;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    .tableTitle {
      width: 100%;
      height: 64px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ececec;
      padding: 0 20px;
      margin-bottom: 10px;
      .title {
        width: 80%;
        height: 100%;
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: 550;
      }
      .addButton {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }
    .tableList {
      // max-height: calc(100vh - 380px);
      // overflow: auto;
      /deep/ .tableScroll {
        max-height: calc(100vh - 380px);
        overflow: auto;
      }
    }
  }
}
#modalContent {
  width: 100%;
  height: 540px;
  overflow: auto;
  position: relative;
  .formAspin {
    position: absolute;
    width: 100%;
    height: 540px;
    background: #ececec;
    border-radius: 4px;
    z-index: 999;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.formTitle {
  width: 100%;
  font-size: 16px;
  color: #40a9ff;
  // padding: 10px 0 5px;
  //border-bottom: 1px solid #d9d9d9;
  border-bottom: 1px solid #40a9ff;
  margin-bottom: 28px;
  padding-bottom: 20px;
}
.feetitle {
  margin-bottom: 20px;
}
.feeChecked {
  margin-left: 20px;
}
/deep/ .ant-col .ant-col-4{
  width: 20.666667%;
}
.tipstext{
  line-height: 40px;
  color: #999999;
  margin: 0 12px;
}
</style>
<style>
.rangeTimePicker .ant-input-disabled {
  background-color: #fff;
  color: rgba(0, 0, 0, 0.65);
  cursor: auto;
}
.rangeTimePicker .ant-calendar-range.ant-calendar-time .ant-calendar-time-picker-inner {
  padding-top: 0;
}
.rangeTimePicker .ant-calendar-time .ant-calendar-footer .ant-calendar-time-picker-btn {
  display: none;
}

</style>
